layui.define([ 'layedit','admin', 'view','validate','baseSetting','inputTag','selfUtils', 'laydate', 'form', 'table','laytpl'], function (exports) {

    var $ = layui.jquery
        ,layedit = layui.layedit
        ,form = layui.form
        ,laytpl = layui.laytpl
        ,inputTag = layui.inputTag
        ,admin = layui.admin
        ,brand = layui.selfUtils
        ,layer = layui.layer
        ,view = layui.view
        ,table = layui.table
        ,laydate = layui.laydate
        ,sortObject = {field: 'createTime'};

    brand.get("/category/list", null, function (res) {
        if (res.status == '400') {
            brand.alert.error(res.message);
            return;
        }
        let getTpl = categoryListTpl.innerHTML
            , viewT = document.getElementById('categoryListContainer');
        laytpl(getTpl).render(res.data, function (html) {
            viewT.innerHTML = html;
        });
        form.render();
    });

    form.render();
    let tableIns;
    initTable();

    laydate.render({
        elem: '#createTime',
        range: true,
        position:'fixed',
        trigger: 'click'
    });
    var width = $(window).width() - $("#my-side").width()+'px';
    var height = $(window).height() - $("#my-header").height()+'px';

    function initTable() {
        tableIns = brand.table.init({
            elem: '#sopTable',
            id: 'sopTable',
            url:  '/sop/list',
            type:'GET',
            cols: [[
                {field: 'title', title: '标题', minWidth: 250,align:'center',fixed:'left'},
                {field: 'content', title: '内容',align:'center'},
                {field: 'categoryName', title: '类别', align:'center'},
                {field: 'triggerWord', title: '触发词',align:'center'},
                {field: 'handler', title: '处理人',align:'center'},
                {field: 'isDelete', title: '是否启用', templet: '#deleteTpl', minWidth: 80, align: 'center'},
                {field: 'createTime', title: '创建时间', minWidth: 180,sort: true,align:'center'},
                {title: '操作', toolbar: '#oper-option', minWidth: 140,align:'center'}
            ]]
        });
    }

    table.on('tool(sopTable)', function (obj) {
        let data = obj.data,
            layEvent = obj.event;

        if (layEvent === 'detail') {
            admin.popup({
                id: 'LAY-theme-sop-detail',
                area :['800px','600px'],
                shadeClose:false,
                shade:0.3,
                anim: 5,
                resize:false,
                title: '查看SOP',
                success: function(){
                    view(this.id).render('sop/sopDetail', data).then(function(){
                        //视图文件请求完毕，视图内容渲染前的回调
                    }).done(function(){
                        //视图文件请求完毕和内容渲染完毕的回调

                        let contentIndex = layedit.build('content', {
                            tool: ['strong', 'italic', 'underline', 'del', '|', 'left', 'center', 'right'],
                            height: 400,
                            width: $("#LAY-theme-sop-detail").width()
                        });
                        layedit.setContent(contentIndex, data.content,false);

                        form.render();
                    });
                }
            });
        }
        if (layEvent === 'edit') {
            admin.popup({
                id: 'LAY-theme-sop-edit',
                area :[width,height],
                shadeClose:false,
                shade:0.3,
                anim: 5,
                resize:false,
                offset: 'rb',
                title: '编辑SOP',
                success: function(){
                    view(this.id).render('sop/sopEdit', data).then(function(){
                        //视图文件请求完毕，视图内容渲染前的回调
                    }).done(function(){
                        //视图文件请求完毕和内容渲染完毕的回调
                        let handler = data.handler;
                        let arr = handler.split(',');
                        inputTag.render({
                            elem: '.tag3',
                            data: arr,//初始值
                            placeholder:'添加处理人，回车确定',
                            onChange: function (value) {
                                $('#handler3').val(JSON.stringify(value));
                            }
                        });
                        let triggerWords = data.triggerWord;
                        let arr2 = triggerWords.split(',');
                        inputTag.render({
                            elem: '.triggerWordTag2',
                            data: arr2,//初始值
                            placeholder:'添加触发词，回车确定',
                            onChange: function (value) {
                                $('#triggerWord2').val(JSON.stringify(value));
                            }
                        });

                        brand.get('/category/list',null,function (res) {
                            let data2 = {"list":res.data,"categoryId":data.categoryId};
                            let getTpl = categoryListTpl3.innerHTML
                                , viewT = document.getElementById('categoryListContainer3');
                            laytpl(getTpl).render(data2, function (html) {
                                viewT.innerHTML = html;
                            });
                            form.render("select")
                        });

                        form.on('submit(submitSopEdit)', function (data) {
                            // 获取富文本的内容
                            let content = layui.layedit.getContent(contentIndex);
                            data.field['content'] = content;
                            let triggerWord = data.field['triggerWord'];
                            data.field['triggerWord'] = triggerWord.replaceAll("[","").replaceAll("]","").replaceAll("\"","")
                            let handler = data.field['handler'];
                            data.field['handler'] = handler.replaceAll("[","").replaceAll("]","").replaceAll("\"","");
                            brand.put("/sop/updateSop", data.field, function (res) {
                                if (res.status != '200') {
                                    // 失败
                                    brand.alert.error(res.message);
                                    return false;
                                }
                                brand.alert.success(res.message, {
                                    end: function () {
                                        $("#refreshBtn").click();
                                    }
                                });
                            });
                            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                        });

                        let contentIndex = layedit.build('content2', {
                            tool: ['strong', 'italic', 'underline', 'del', '|', 'left', 'center', 'right'],
                            height: $("#LAY-theme-sop-edit").height()*0.5,
                            width: $("#soptitle").width()
                        });
                        layedit.setContent(contentIndex, data.content,true);

                        form.render();
                    });
                }
            });
        }
    });

    form.on('switch(isDelete)', function(data){
        let text = data.elem.checked ? '启用':'弃用';
        brand.modal.confirm(text+' SOP',"您正在【"+text+"】该SOP，您确定吗？", function (index) {
            brand.del("/sop/deprecatedSop",{"isDelete":text==='启用'?0:1,"id":data.value},function (res) {
                if(res.status == 200){
                    brand.alert.success('【'+text+'】成功^_^');
                }else{
                    brand.alert.error('【'+text+'】失败~_~');
                    if(text === '启用')
                        data.elem.checked = false;
                    else
                        data.elem.checked = true;
                }
                form.render();
                layer.close(index);
            });
        },function (index) {
            if(text === '启用') {
                data.elem.checked = false;
            } else {
                data.elem.checked = true;
            }
            form.render();
            layer.close(index);
        },{});
    });

    $("#addSop").on("click",function () {
        admin.popup({
            id: 'LAY-theme-sop-add',
            area :[width,height],
            shadeClose:false,
            shade:0.3,
            anim: 5,
            resize:false,
            offset: 'rb',
            title: '添加SOP',
            success: function(){
                view(this.id).render('sop/sopAdd', {}).then(function(){
                    //视图文件请求完毕，视图内容渲染前的回调
                }).done(function(){
                    //视图文件请求完毕和内容渲染完毕的回调
                    inputTag.render({
                        elem: '.tag1',
                        data: [],//初始值
                        placeholder:'添加处理人，回车确定',
                        onChange: function (value) {
                            $('#handler').val(JSON.stringify(value));
                        }
                    });

                    inputTag.render({
                        elem: '.triggerWordTag',
                        data: [],//初始值
                        placeholder:'添加触发词，回车确定',
                        onChange: function (value) {
                            $('#triggerWord').val(JSON.stringify(value));
                        }
                    });

                    brand.get("/category/list", null, function (res) {
                        if (res.status != '200') {
                            brand.alert.error(res.message);
                            return;
                        }
                        let getTpl = categoryListTpl2.innerHTML
                            , viewT = document.getElementById('categoryListContainer2');
                        laytpl(getTpl).render(res.data, function (html) {
                            viewT.innerHTML = html;
                        });
                        form.render();
                    });


                    form.render();
                });
            }
        });
    });

    $("#query").on('click', function () {
        var params = $.extend(getQueryParams(), {field: sortObject.field, order: sortObject.type});
        tableIns.reload({where: params, page: {curr: 1}});
    });

    $("#reset").on('click', function () {
        $('#robot-sop').find('form')[0].reset();
        $('#refreshBtn').click();
        // tableIns.reload({where: getQueryParams(), page: {curr: 1}, initSort: sortObject});
    });

    function getQueryParams() {
        var createTimeFrom='',
            createTimeTo='',
            createTime = $("#taskConfig-query").find('input[name="createTime"]').val();
        if (createTime) {
            createTimeFrom = createTime.split(' - ')[0];
            createTimeTo = createTime.split(' - ')[1];
        }
        return $.extend({
            createTimeFrom: createTimeFrom,
            createTimeTo: createTimeTo,
        },form.val("sop-query-form"));
    }
    //对外暴露的接口
    exports('sop/sop', {});

});
